package com.jpyl.jpMedicalTreatment.view.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.forxindu.kit.box.JavaKit;
import com.forxindu.kit.box.VerifyKit;
import com.forxindu.kit.box.ViewKit;
import com.jpyl.jpMedicalTreatment.R;
import com.jpyl.jpMedicalTreatment.common.MedicalSettings;

import butterknife.BindView;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

public class FindPasswordActivity extends BaseActivity {


    @BindView(R.id.number_phone)
    EditText phoneNumber;

    @BindView(R.id.auth_code)
    EditText authCode;

    @BindView(R.id.sendCodeBtn)
    Button sendCodeBtn;

    @BindView(R.id.make_sure_btn)
    Button makeSureBtn;

    private String username;

    EventHandler eventHandler = new EventHandler() {
        public void afterEvent(int event, int result, Object data) {
            // afterEvent会在子线程被调用，因此如果后续有UI相关操作，需要将数据发送到UI线程
            Message msg = new Message();
            msg.arg1 = event;
            msg.arg2 = result;
            msg.obj = data;
            new Handler(Looper.getMainLooper(), new Handler.Callback() {
                @Override
                public boolean handleMessage(Message msg) {
                    int event = msg.arg1;
                    int result = msg.arg2;
                    Object data = msg.obj;
                    if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        if (result == SMSSDK.RESULT_COMPLETE) {
                            // TODO 处理成功得到验证码的结果
                            // 请注意，此时只是完成了发送验证码的请求，验证码短信还需要几秒钟之后才送达
                            ViewKit.showToast(FindPasswordActivity.this, "验证码已发送");
                        } else {
                            // TODO 处理错误的结果
                            ((Throwable) data).printStackTrace();
                        }
                    } else if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        if (result == SMSSDK.RESULT_COMPLETE) {
                            // TODO 处理验证码验证通过的结果
                            Intent intent = new Intent(FindPasswordActivity.this,ResetPasswordActivity.class);
                            intent.putExtra(MedicalSettings.MEMBER_MOBILE,username);
                             startActivity(intent);
                        } else {
                            // TODO 处理错误的结果
                            ((Throwable) data).printStackTrace();
                            ViewKit.showToast(FindPasswordActivity.this, "验证码错误");
                        }
                    }
                    // TODO 其他接口的返回结果也类似，根据event判断当前数据属于哪个接口
                    return false;
                }
            }).sendMessage(msg);
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_find_password;
    }

    @Override
    public void afterCreate(Bundle savedInstanceState) {
        // 注册一个事件回调，用于处理SMSSDK接口请求的结果
        SMSSDK.registerEventHandler(eventHandler);
        sendCodeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                username = phoneNumber.getText().toString().trim();
                if (JavaKit.isStringEmpty(username)) {
                    ViewKit.showToast(FindPasswordActivity.this, getString(R.string.login_mobile));
                    return;
                }
                if (!VerifyKit.isMobile(username)) {
                    ViewKit.showToast(FindPasswordActivity.this, getString(R.string.find_password_correct_mobile));
                    return;
                }
                countDown();
                phoneNumber.setFocusable(false);
                phoneNumber.setFocusableInTouchMode(false);
                // 请求验证码，其中country表示国家代码，如“86”；phone表示手机号码，如“13800138000”
                SMSSDK.getVerificationCode("86", username);
            }
        });

        makeSureBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                username = phoneNumber.getText().toString().trim();
                final String authCodeText = authCode.getText().toString().trim();
                if (TextUtils.isEmpty(username)) {
                    ViewKit.showToast(FindPasswordActivity.this, getResources().getString(R.string.user_name_cannot_be_empty));
                    return;
                }
                if (TextUtils.isEmpty(authCodeText)) {
                    ViewKit.showToast(FindPasswordActivity.this, "验证码不能为空");
                    return;
                }
                // 提交验证码，其中的code表示验证码，如“1357”
                SMSSDK.submitVerificationCode("86", username, authCodeText);
            }
        });
    }

    /**
     * 倒数计时
     */
    @SuppressLint("ResourceAsColor")
    private void countDown() {
        new CountDownTimer(MedicalSettings.COUNT_DOWN_TIME, 1000) {

            public void onTick(long millisUntilFinished) {
                String againSendInfo = getResources().getString(R.string.find_password_again_send_info);
                String againSendInfoText = String.format(againSendInfo, String.valueOf(millisUntilFinished / 1000));
                sendCodeBtn.setText(Html.fromHtml(againSendInfoText));
                sendCodeBtn.setBackgroundResource(R.drawable.round_corner_gray_ebebeb_bg_shape10);
                sendCodeBtn.setTextColor(getResources().getColor(R.color.gray_AAAAAA));
                sendCodeBtn.setClickable(false);
            }

            public void onFinish() {
                sendCodeBtn.setText(getString(R.string.find_password_auth_code));
                sendCodeBtn.setBackgroundResource(R.drawable.round_corner_blue_bg_shape30);
                sendCodeBtn.setTextColor(getResources().getColor(R.color.white));
                sendCodeBtn.setClickable(true);
            }
        }.start();
    }
}
